package demo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;

import java.util.ArrayList;
import java.util.List;

public class FlightInfoParser {
    public static void main(String[] args) throws DocumentException {

        // 创建一个 SAXReader 对象
        SAXReader reader = new SAXReader();

        //指定需要解析的XML文件路径
        String xml="src/main/java/demo/Demo.xml";

        //解析XML文件将航班信息返回集合中
        List<Flight> flights = parseFlights(xml);

        // 输出航班信息
        for (Flight flight : flights) {
            System.out.println("航班信息：");
            System.out.println("航空公司：" + flight.getCompany());
            System.out.println("起飞机场：" + flight.getStartDrome());
            System.out.println("到达机场：" + flight.getArriveDrome());
            System.out.println("起飞时间：" + flight.getStartTime());
            System.out.println("到达时间：" + flight.getArriveTime());
            System.out.println("机型：" + flight.getMode());
            System.out.println("是否经停：" + flight.getAirlineStop());
        }
    }
    public static List<Flight> parseFlights(String xml) {
        List<Flight> flights = new ArrayList<>();

        try {
            // 创建一个 SAXReader 对象
            SAXReader reader = new SAXReader();
            //指定需要解析的XML文件路径
             xml="src/main/java/demo/Demo.xml";

            //读取XML文件，获得Document对象
            Document document=reader.read(new File(xml));

            // 获取 XML 文件的根节点
            Element root = document.getRootElement();

            // 获取根节点下的所有子节点
            List<Element> airlineList = root.elements("airlines");

            for (Element airline : airlineList) {
                // 创建航班对象
                Flight flight = new Flight();
                // 设置航班信息
                flight.setId(Integer.parseInt(airline.elementText("id")));
                flight.setCompany(airline.elementText("Company"));
                flight.setStartDrome(airline.elementText("StartDrome"));
                flight.setArriveDrome(airline.elementText("ArriveDrome"));
                flight.setStartTime(airline.elementText("StartTime"));
                flight.setArriveTime(airline.elementText("ArriveTime"));
                flight.setMode(Integer.parseInt(airline.elementText("Mode")));
                flight.setAirlineStop(Integer.parseInt(airline.elementText("AirlineStop")));
                // 添加航班对象到集合中
                flights.add(flight);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return flights;
    }
}

